package moe.server;

import java.lang.ref.SoftReference;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import moe.entity.Post;

public class ImageCache {
	public static final String CACHE_CONTEXT = "Cache";

	public static enum CacheType {
		FORWARD, BACKWARD, UNKNOW
	}

	private Map<String, SoftReference<byte[]>> cache =
			new ConcurrentHashMap<String, SoftReference<byte[]>>();
	//private Map<String, byte[]> cache = new ConcurrentHashMap<String, byte[]>();

	private CacheType cacheType = CacheType.UNKNOW;
	private String trackId, currentId;

	private Map<String, String[]> query;
	private List<Post> posts;

	/*
		public boolean containsKey(String key) {
			return cache.containsKey(key);
		}

		public byte[] get(String key) {
			return cache.get(key);
		}

		public byte[] put(String key, byte[] value) {
			return cache.put(key, value);
		}

		public byte[] remove(String key) {
			return cache.remove(key);
		}
	*/

	public boolean containsKey(String key) {
		boolean result = cache.containsKey(key);
		if (result) {
			SoftReference<byte[]> ref = cache.get(key);
			if (ref.get() == null) {
				result = false;
				cache.remove(key);
			}
		}
		return result;
	}

	public byte[] get(String key) {
		SoftReference<byte[]> ref = cache.get(key);
		byte[] result = null;
		if (ref != null) {
			result = ref.get();
			if (result == null) {
				cache.remove(key);
			}
		}
		return result;
	}

	public byte[] put(String key, byte[] value) {
		SoftReference<byte[]> ref = new SoftReference<byte[]>(value);
		ref = cache.put(key, ref);
		if (ref == null) {
			return null;
		}
		return ref.get();
	}

	public byte[] remove(String key) {
		SoftReference<byte[]> ref = cache.remove(key);
		if (ref == null) {
			return null;
		}
		return ref.get();
	}

	public void clear() {
		cache.clear();
	}

	public int size() {
		return cache.size();
	}

	public CacheType getCacheType() {
		return cacheType;
	}

	public void setCacheType(CacheType type) {
		cacheType = type;
	}

	public String getTrackId() {
		return trackId;
	}

	public void setTrackId(String id) {
		trackId = id;
	}

	public String getCurrentId() {
		return currentId;
	}

	public void setCurrentId(String id) {
		currentId = id;
	}

	public List<Post> getPostList() {
		return posts;
	}

	public void setPostList(List<Post> posts) {
		this.posts = posts;
	}

	public Map<String, String[]> getQuery() {
		return query;
	}

	public void setQuery(Map<String, String[]> query) {
		this.query = query;
	}

}
